package com.example.testdbsearchform;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class CategoryDAO {

	// Database fields
	  private SQLiteDatabase database;
	  public CategoryDAO(SQLiteDatabase database) {
		  this.database = database;
	  }

	  public Category createCategory(String name) {
	    ContentValues values = new ContentValues();
	    values.put("name", name);
	    long insertId = database.insert("Category", null, values);
	    
	    Cursor cursor = database.
	    		  rawQuery("select * from Category where _id = ? ", 
	    				  new String[] { Long.toString(insertId) });
	    
	    if (!cursor.moveToFirst()) {
	    	return null;
	    }
	    Category newCategory = cursorToCategory(cursor);
	    cursor.close();
	    return newCategory;
	  }

	  public void deleteCategory(Category Category) {
	    long id = Category.getId();
	    System.out.println("Category deleted with id: " + id);
	    database.delete("Category", "_id = " + id, null);
	  }

	  public List<Category> getAllCategorys() {
	    List<Category> Categorys = new ArrayList<Category>();

	    Cursor cursor = database.
	    		  rawQuery("select * from Category ", new String[] {});
	    
	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	      Category Category = cursorToCategory(cursor);
	      Categorys.add(Category);
	      cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
	    return Collections.unmodifiableList(Categorys);
	  }

	  private Category cursorToCategory(Cursor cursor) {
	    Category Category = new Category();
	    Category.setId(cursor.getLong(0));
	    Category.setName(cursor.getString(1));
	    return Category;
	  }
}
